#ifndef DRE_BUS_SAFE_H_
#define DRE_BUS_SAFE_H_

#include "config.h"

#define	DRE_SD	0xE8u   //帧头
#define	DRE_ED	0xE0u   //帧尾


// SPI数据帧
typedef struct _exch_com_run_dat{
	uint8_t				u8_sd; //数据头
	uint8_t				u8_fc; //功能码
	uint16_t       u16_crc_config;   //用户组态的crc校验数据
  run_SPI_data_t     com_run_display_data;//运行数据
  run_SPI_data_t     com_run_display_data_rev;//运行数据取反	
	uint16_t			 u16_diag_step;    //用于脉冲诊断的步数  
	uint16_t			 u16_mcua_di;    //MCUA和MCUB采集到DI信号
	uint16_t			 u16_mcub_di; 
	uint16_t			 u16_mcua_do;    //MCUA和MCUB要输出的信号
	uint16_t			 u16_mcub_do; 
	uint16_t       u16_OutputCheckSM;  //输出自检测试同步标志
  uint16_t       u16_crc_frame;    //该通讯帧的crc校验数据
  uint8_t        u8_le; //数据长度，固定值
	uint8_t				 u8_ed; //数据尾
}exch_com_run_dat_t;


//用来传输组态数据的SPI/UART命令帧
typedef enum _dre_safe_sta{
    DRE_IDLE	= 0x01,
    DRE_START	= 0x02,
    DRE_WAIT	= 0x03,
    DRE_XFER	= 0x04,
}dre_safe_sta_t;

typedef struct _dre_safe_err_sta{
	uint32_t	u32_timeout_cnt	;
	uint16_t	u16_tim_old		;
	uint16_t	u16_err_cnt		;
	bool_t		b8_err			;
}dre_safe_err_sta_t;

typedef struct _dre_safe_info{
	dre_safe_sta_t		em_sf_sta;
	dre_safe_err_sta_t	st_sf_err;
	uint16_t			u16_step_tx;
	uint16_t			u16_step_rx;
	uint16_t			u16_step_ack;
	tim_dat_t			st_syn_tim;
}dre_safe_info_t;

#define	DRE_SAFE_TIMEOUT	3000u	/* 300ms, unit is 0.1ms */
#define	DRE_SAFE_MAX_ERR	32u   /* 16 -> 32 辐射测试 */
#define	DRE_PHYS_TIMEOUT	750u	/* 75ms, unit is 0.1ms */
#define	DRE_SYN_TIME		20u		/* 2ms, unit is 0.1ms */
#define	DRE_SYN_STEP_MAX	800u

void dre_init(bool_t b8_is_master);

void dre_init_val(void);
void dre_safe_reco(void);
void dre_syn_handle(uint8_t u8_mcu_addr);
bool_t dre_compare_safe_dat(uint8_t u8a_dat[], uint8_t u8a_rev[], uint16_t u16_len);

static void dre_fill_tx_dat(exch_com_run_dat_t	*stp_spi_dat, uint8_t u8_fc );

static void dre_get_rx_dat(exch_com_run_dat_t	*stp_spi_dat);

void dre_protocol_poll(void);

void dre_safe_poll(const uint8_t u8lc_init_val, const uint8_t u8lc_incr_val);

uint16_t dre_get_diag_tx_step(void);
uint16_t dre_get_diag_rx_step(void);
void dre_set_diag_tx_step(uint16_t u16_step);
void dre_set_diag_ack_step(uint16_t u16_step);

#endif
